package com.skz;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

public class CallableTest {

    public static void test3() throws InterruptedException, ExecutionException {
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        ExecutorCompletionService<String> completionService = new ExecutorCompletionService<>(executorService);
        for (int i = 0; i < 10; i++) {
            final int taskNum = i;
            completionService.submit(() -> "200 ok" + taskNum);
        }
        for (int i = 0; i < 10; i++) {
            Future<String> take = completionService.take();
            System.out.println(take.get());
        }
    }

    public static void test2() throws InterruptedException {
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        List<Future> futureTasks = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            final int taskNum = i;
            //异步批量提交任务执行
            Future<String> task = executorService.submit(new Callable<String>() {
                @Override
                public String call() throws Exception {
                    Thread.sleep(1000);//模拟任务执行
                    return "200 ok" + taskNum;
                }
            });
            //保存结果钩子
            futureTasks.add(task);
            System.out.println("任务" + taskNum + "添加到队列。");
        }
        //模拟主线程执行
        Thread.sleep(2000);
        futureTasks.forEach(future -> {
            try {
                //获取异步任务结果
                System.out.println(future.get());
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }
        });
    }

    public static void test1() {
        FutureTask<String> stringFutureTask = new FutureTask<>(() -> {
            Thread.sleep(1000);
            return "200 ok";
        });
        new Thread(stringFutureTask).start();
        try {
            System.out.println("等待获取结果");
            System.out.println(stringFutureTask.get());
        } catch (ExecutionException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}
